<template>
  <a-button @click="router.back" type="outline" status="success">
    <icon-left />
    返回
  </a-button>
  <div class="case-container" id="addQuestionCaseView">
    <h2 style="text-align: center; margin-bottom: 24px">
      {{ updatePage ? "修改测试用例" : "新增测试用例" }}
    </h2>
    <div class="case-content">
      <!-- 左侧参数列表 -->
      <div class="case-column">
        <h3>输入参数</h3>
        <div class="param-add">
          <a-input v-model="inputParam" placeholder="输入参数值" />
          <a-button type="primary" @click="handleAddParam">添加参数</a-button>
        </div>
        <div class="param-list-container">
          <a-list bordered :data="argumentInputs">
            <template #item="{ item, index }">
              <a-list-item>
                <div class="list-item-content">
                  <span class="param-text">{{ item }}</span>
                  <a-button
                    type="text"
                    status="danger"
                    @click="handleDeleteParam(index)"
                    class="delete-btn"
                  >
                    <icon-delete />
                    删除
                  </a-button>
                </div>
              </a-list-item>
            </template>
          </a-list>
        </div>
      </div>

      <!-- 中间文件上传 -->
      <div class="case-column">
        <h3>输入文件</h3>
        <div class="param-add">
          <a-upload
            :custom-request="handleFileInputUpload"
            :show-file-list="false"
          >
            <a-button type="primary">
              <icon-upload />
              上传输入文件
            </a-button>
          </a-upload>
        </div>
        <div class="param-list-container">
          <a-list bordered :data="inputFiles">
            <template #item="{ item, index }">
              <a-list-item>
                <div class="list-item-content">
                  <span class="param-text">{{ item }}</span>
                  <a-button
                    type="text"
                    status="danger"
                    @click="handleDeleteInputFile(index)"
                    class="delete-btn"
                  >
                    <icon-delete />
                    删除
                  </a-button>
                </div>
              </a-list-item>
            </template>
          </a-list>
        </div>
      </div>

      <!-- 右侧组合 -->
      <div class="case-column">
        <div class="right-section">
          <h3>预期输出</h3>
          <a-textarea
            v-model="output"
            placeholder="输入预期输出"
            :auto-size="{
              minRows: 9,
              maxRows: 9,
            }"
            class="tall-input"
          />
        </div>
        <div class="right-section">
          <h3>输出文件</h3>
          <a-upload
            :custom-request="handleFileOutputUpload"
            :show-file-list="false"
          >
            <a-button type="primary">
              <icon-upload />
              上传输出文件
            </a-button>
          </a-upload>
          <div v-if="outputFile" class="file-display">
            <div class="file-item">
              <icon-file class="file-icon" />
              <span class="file-name">{{ outputFile }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="submit-button">
      <a-button type="primary" @click="handleSubmit">提交</a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { RequestOption, UploadRequest } from "@arco-design/web-vue";
import {
  FileControllerService,
  QuestionCaseAddRequest,
  QuestionCaseControllerService,
  QuestionCaseEditRequest,
} from "../../../api";
import message from "@arco-design/web-vue/es/message";
// 正确初始化路由对象
// 在 setup 顶部获取 route 实例
const route = useRoute();
const router = useRouter();
const updatePage = route.path.includes("update");

// 获取题目ID
const questionId = ref(Number(route.query.id));

// 左侧参数输出相关
const inputParam = ref("");
const argumentInputs = ref<string[]>([]);

// 中间文件相关
const inputFiles = ref<string[]>([]);

// 右侧相关
const output = ref("");
const outputFile = ref("");

// 在原有script部分添加删除方法
const handleDeleteParam = (index: number) => {
  argumentInputs.value.splice(index, 1);
};

// 删除输入文件
const handleDeleteInputFile = (index: number) => {
  inputFiles.value.splice(index, 1);
};

const handleAddParam = () => {
  if (inputParam.value.trim()) {
    argumentInputs.value.push(inputParam.value);
    inputParam.value = "";
  }
};

const handleFileInputUpload = (options: RequestOption): UploadRequest => {
  const { fileItem } = options;

  const controller = new AbortController();
  // eslint-disable-next-line no-async-promise-executor
  new Promise(async () => {
    // 这里替换为真实的上传逻辑
    if (!fileItem.file) {
      message.error("请先选择上传文件");
      return;
    }
    const res = await FileControllerService.upload({
      file: fileItem.file,
    });
    if (res.code === 0) {
      inputFiles.value.push(res.data ?? "");
    } else {
      message.error(res.message || "上传失败");
    }
  });
  // 返回符合要求的UploadRequest对象
  return {
    abort: () => {
      controller.abort();
      console.log("Upload canceled");
    },
  };
};

const handleFileOutputUpload = (options: RequestOption): UploadRequest => {
  const { fileItem } = options;

  const controller = new AbortController();
  // eslint-disable-next-line no-async-promise-executor
  new Promise(async () => {
    if (!fileItem.file) {
      message.error("请先选择上传文件");
      return;
    }
    const res = await FileControllerService.upload({
      file: fileItem.file,
    });
    if (res.code === 0) {
      outputFile.value = res.data ?? "";
    } else {
      message.error(res.message || "上传失败");
    }
  });
  // 返回符合要求的UploadRequest对象
  return {
    abort: () => {
      controller.abort();
      console.log("Upload canceled");
    },
  };
};

const handleSubmit = async () => {
  let form = ref<QuestionCaseAddRequest>({
    questionId: questionId.value, // 使用响应式变量
    argumentsInput: argumentInputs.value,
    fileInput: inputFiles.value,
    output: output.value,
    fileOutput: outputFile.value,
  });
  if (updatePage) {
    let updateRequest = ref<QuestionCaseEditRequest>({
      id: 0,
      argumentsInput: [],
      fileInput: [],
      output: "",
      fileOutput: "",
    });
    updateRequest.value.id = Number(route.query.id);
    updateRequest.value.argumentsInput = argumentInputs.value;
    updateRequest.value.fileInput = inputFiles.value;
    updateRequest.value.output = output.value;
    updateRequest.value.fileOutput = outputFile.value;
    const res = await QuestionCaseControllerService.updateQuestionCase(
      updateRequest.value
    );
    if (res.code === 0) {
      message.success("更新成功");
      await router.push({
        path: "/manage/question_case",
        query: {
          id: questionId.value,
        },
      });
    } else {
      message.error("更新失败，" + res.message);
    }
    return;
  }
  const res = await QuestionCaseControllerService.addQuestionCase(form.value);
  if (res.code === 0) {
    message.success("创建成功");
    await router.push({
      path: "/manage/question_case",
      query: { id: questionId.value },
    });
  } else {
    message.error("创建失败，" + res.message);
  }
};

const loadData = async () => {
  const id = route.query.id;
  if (!id || !updatePage) {
    return;
  }
  // eslint-disable-next-line
  const res = await QuestionCaseControllerService.getQuestionCase(id as any);
  if (res.code === 0) {
    output.value = res.data?.output ?? "";
    outputFile.value = res.data?.fileOutput ?? "";
    questionId.value = res.data?.questionId ?? 0;
    if (res.data?.argumentsInput) {
      argumentInputs.value = JSON.parse(res.data.argumentsInput);
    } else {
      argumentInputs.value = [];
    }
    if (res.data?.fileInput) {
      inputFiles.value = JSON.parse(res.data.fileInput);
    } else {
      inputFiles.value = [];
    }
  } else {
    message.error("加载失败，" + res.message);
  }
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.case-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.case-content {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
}

/* 新增容器样式 */
/* 调整列表项高度 */

.param-list-container {
  height: 273px;
  overflow-y: auto;
  border-radius: 4px;
}

/* 保持原有样式优化 */
.list-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
}

.param-text {
  flex: 1;
  margin-right: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.delete-btn {
  flex-shrink: 0;
  margin-left: 8px;
}

/* 滚动条样式优化 */
.param-list-container::-webkit-scrollbar {
  width: 6px;
}

.param-list-container::-webkit-scrollbar-track {
  background: var(--color-fill-2);
}

.param-list-container::-webkit-scrollbar-thumb {
  background: var(--color-fill-4);
  border-radius: 4px;
}

.param-list-container::-webkit-scrollbar-thumb:hover {
  background: var(--color-fill-4);
}

.case-column {
  flex: 1;
  padding: 16px;
  border: 1px solid var(--color-border);
  border-radius: 4px;
}

.right-section {
  margin-bottom: 24px;
}

.param-add {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.file-name {
  margin-top: 8px;
  color: var(--color-text-2);
}

.submit-button {
  text-align: center;
}

.tall-input {
  height: 200px; /* 固定高度 */
  min-height: 120px; /* 最小高度 */
}

/* outputFile样式 */
.file-display {
  margin-top: 12px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background-color: var(--color-fill-2);
  border-radius: 4px;
  border: 1px solid var(--color-border-2);
}

.file-icon {
  color: var(--color-text-3);
  font-size: 18px;
}

.file-name {
  flex: 1;
  font-size: 14px;
  line-height: 1;
  margin-top: 1px;
  color: var(--color-text-1);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
